package com.aier.admin.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.aier.admin.entity.mapper.BuyMessageRowMapper;
import com.aier.admin.service.IAdminBuyService;
import com.aier.common.common.AierDateUtil;
import com.aier.common.common.Constant;
import com.aier.common.dao.ICommonDAO;
import com.aier.school.entity.mapper.SchoolRowMapper;
import com.aier.user.entity.User;
import com.aier.user.entity.mapper.UserRowMapper;
import com.aier.user.entity.userapp.UserModule;
import com.aier.user.entity.userapp.UserModuleRowMapper;

@Component("adminBuyService")
public class AdminBuyServiceImpl_J implements IAdminBuyService {

    @Resource(name="commonDao")
    private ICommonDAO commonDao;
    public void setCommonDao(ICommonDAO commonDao) {
        this.commonDao = commonDao;
    }
    
    @Override
    public Map<String, Object> searchSchoolList(String sname,Integer cid,int page, int page_size) {
        String sql = "";
        List<Object> largcount = new ArrayList<Object>();
        if (null!=sname && !"".equals(sname)) {
            sql += " where s.`name` like ?";
            largcount.add("%" + sname + "%");
            if (null!=cid && cid != -1) {
                sql += " and FIND_IN_SET(s.cid, getChildLst(?))";
                largcount.add(cid);
            }
        } else {
            if (null!=cid && cid != -1) {
                sql += " where FIND_IN_SET(s.cid, getChildLst(?))";
                largcount.add(cid);
            }
        }
        sql += " order by s.sid";
        
        
        return commonDao.queryPage("select s.*,(select count(DISTINCT(cp.uid)) from class_parent cp INNER JOIN classes c on cp.cid=c.cid " +
        		"where c.sid=s.sid) " +
            		"as num_parent from school s "+sql,
                        page, page_size, largcount,
                         new SchoolRowMapper(SchoolRowMapper.AND_PARENTNUMS));
    }
    
    @Override
    public Map<String, Object> searchSchoolListNew(String sname,Integer cid,Integer method,int page, int page_size) {
        String sql = "";
        List<Object> largcount = new ArrayList<Object>();
        if (null!=sname && !"".equals(sname)) {
            sql += " where s.`name` like ?";
            largcount.add("%" + sname + "%");
            if (null!=cid && cid != -1) {
                sql += " and FIND_IN_SET(s.cid, getChildLst(?))";
                largcount.add(cid);
                if (null!=method && method != -1) {
                    sql += " and s.method = ?";
                    largcount.add(method);
                }
            }else {
                if (null!=method && method != -1) {
                    sql += " where s.method = ?";
                    largcount.add(method);
                }
            }
        } else {
            if (null!=cid && cid != -1) {
                sql += " where FIND_IN_SET(s.cid, getChildLst(?))";
                largcount.add(cid);
                if (null!=method && method != -1) {
                    sql += " and s.method = ?";
                    largcount.add(method);
                }
            } else {
                if (null!=method && method != -1) {
                    sql += " where s.method = ?";
                    largcount.add(method);
                }
            }
        }
        sql += " order by s.method desc, s.mesCount desc";
        
        
        return commonDao.queryPage("select s.*,(select count(DISTINCT(cp.uid)) from class_parent cp INNER JOIN classes c on cp.cid=c.cid " +
                "where c.sid=s.sid) " +
                    "as num_parent from school s "+sql,
                        page, page_size, largcount,
                         new SchoolRowMapper(SchoolRowMapper.AND_BUY));
    }

    @SuppressWarnings("deprecation")
    @Override
    public int insertServiceBySchool(Long sid, Integer method, String edate) {
        @SuppressWarnings("unchecked")
        List<String> uidList = (List<String>) commonDao.list(
                "select DISTINCT(cp.uid) from class_parent cp left join classes c on cp.cid = c.cid left join school s on c.sid = s.sid " +
                "where s.sid = ?", 
                new Object[] {sid}, new RowMapper<String>() {
                    @Override
                    public String mapRow(ResultSet rs, int arg1)
                        throws SQLException {
                        return rs.getString("uid");
                    }
                });
        for (int i = 0;i<uidList.size(); i++) {
            UserModule um = (UserModule) commonDao.listByObject("select * from userapp_user_module where uid = ?", 
                    new Object[]{uidList.get(i)}, new UserModuleRowMapper());
            String newedate = "";
            SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
            if (um == null) {
                // 用户没有购买过服务
                if (method == 1) {
                    Date date = new Date();
                    date.setMonth(date.getMonth() + Integer.valueOf(edate));
                    newedate = df.format(date);
                } else {
                    newedate = edate;
                }
                // 添加记录
                commonDao.update("insert into userapp_user_module(uid,mid,edate) values(?,?,?)",
                        new Object[]{uidList.get(i),1,newedate});
                
            } else {
                // 用户之前购买过服务
                if (method == 1) {
                    Date date = um.getEdate();
                    date.setMonth(date.getMonth() + Integer.valueOf(edate));
                    newedate = df.format(date);
                } else {
                    newedate = edate;
                }
                // 更新记录
                commonDao.update("update userapp_user_module set edate = ? where uid = ? and mid = 1",
                        new Object[]{newedate,um.getUid()});
            }
            
        }
        // 更新学校购买服务的方式
        commonDao.update("UPDATE school s SET s.method=1 WHERE s.sid=?",
                new Object[] {sid});
        
        return 1;
    }

    @Override
    public Map<String, Object> searchUserList(String account,String sdate, int page,
            int page_size) {
        String sql = "";
        List<Object> largcount = new ArrayList<Object>();
        if (null!=account && !"".equals(account)) {
            sql += " and u.account like ?";
            largcount.add("%" + account + "%");
        }
        if (null!=sdate && !"".equals(sdate)) {
            sql += " and u.account = ?";
            largcount.add(sdate);
        }
        sql += " order by u.uid";
        
        
        return commonDao.queryPage("select u.*,um.edate from user u left join userapp_user_module um on u.uid = um.uid where isbaby = 0"+sql,
                        page, page_size, largcount,
                         new UserRowMapper(UserRowMapper.SERVICE));
    }

    @SuppressWarnings("deprecation")
    @Override
    public int insertServiceByUser(Long uid, Integer method, String edate) {
        UserModule um = (UserModule) commonDao.listByObject("select * from userapp_user_module where uid = ?", 
                new Object[]{uid}, new UserModuleRowMapper());
        String newedate = "";
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        if (um == null) {
            // 用户没有购买过服务
            if (method == 1) {
                Date date = new Date();
                date.setMonth(date.getMonth() + Integer.valueOf(edate));
                newedate = df.format(date);
            } else {
                newedate = edate;
            }
            // 添加记录
            commonDao.update("insert into userapp_user_module(uid,mid,edate) values(?,?,?)",
                    new Object[]{uid,1,newedate});
            
        } else {
            // 用户之前购买过服务
            if (method == 1) {
                Date date = um.getEdate();
                date.setMonth(date.getMonth() + Integer.valueOf(edate));
                newedate = df.format(date);
            } else {
                newedate = edate;
            }
            // 更新记录
            commonDao.update("update userapp_user_module set edate = ? where uid = ? and mid = 1",
                    new Object[]{newedate,uid});
        }
        return 1;
    }

    @Override
    public int deleteServiceByUser(Long uid) {
        return commonDao.update("delete from userapp_user_module where uid = ?", new Object[]{uid});
    }

    @SuppressWarnings("deprecation")
    @Override
    public int insertNewService(Long uid, String account) {
        UserModule um = (UserModule) commonDao.listByObject("select * from userapp_user_module where uid = ?", 
                new Object[]{uid}, new UserModuleRowMapper());
        // 旧用户没有服务
        if (um == null) {
            return Constant.num_10001;
        }
        // 旧用户的服务已过期
        java.util.Date nowdate=new java.util.Date(); 
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        
        boolean flag = um.getEdate().before(nowdate);
        if(flag) {
            return Constant.num_10002;
        } 
        
        User u = (User)commonDao.listByObject("select * from user where account = ?", new Object[]{account},new UserRowMapper());
        // 新用户不存在
        if (u == null) {
            return Constant.num_10003;
        }
        
        UserModule num = (UserModule) commonDao.listByObject("select * from userapp_user_module where uid = ?", 
                new Object[]{u.getUid()}, new UserModuleRowMapper());
        
        if (num == null) {
            // 新用户没有购买过服务,添加记录
            commonDao.update("insert into userapp_user_module(uid,mid,edate) values(?,?,?)",
                    new Object[]{u.getUid(),1,um.getEdate()});
        } else {
            // 用户之前购买过服务
            String newedate = "";
            int days = 0;
            try {
                days = AierDateUtil.daysBetween(nowdate, um.getEdate());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            // 新用户的服务已过期，从当日开始算
            if (num.getEdate().before(nowdate)) {
                newedate = df.format(um.getEdate());
            } else {
                Date nd = num.getEdate();
                nd.setDate(nd.getDate() + days);
                newedate = df.format(nd);
            }
            
            // 更新记录
            commonDao.update("update userapp_user_module set edate = ? where uid = ? and mid = 1",
                    new Object[]{newedate,u.getUid()});
        }
        // 删除旧用户的服务
        commonDao.update("delete from userapp_user_module where uid = ?",new Object[]{um.getUid()});
        return 1;
    }

    @Override
    public int insertMessageRecord(Long sid, Double price, Integer mcount,
            Double total) {
        Timestamp bdate = new Timestamp(new Date().getTime());
        commonDao.update("INSERT buy_message_record(sid,price,count,total,bdate) value(?,?,?,?,?)",
                new Object[] {sid,price,mcount,total,bdate});
        
        if (commonDao.update("UPDATE school s SET s.mesCount = IFNULL(s.mesCount,0)+?,s.method=2 WHERE s.sid=?",
                new Object[] {mcount,sid})>0) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public Map<String, Object> serachsearchBuyList(Long sid, int page,
            int page_size) {
        
        String sql = "select b.*,s.name from buy_message_record b left join school s on s.sid= b.sid where b.sid=? order by b.bdate desc";
        return commonDao.queryPage(sql,
                    page, page_size, new Object[]{sid},
                     new BuyMessageRowMapper());
    }
    
    
}
